import plugin from '../../../lib/plugins/plugin.js'
import fetch from 'node-fetch'
import { checkCD, cancelCD } from "../model/CD.js"
import { getStatus, modifyText } from "../model/SR.js"
import { funs, getFunAndParams } from "../components/index.js"

export class impact extends plugin {
    constructor() {
        super({
            /** 功能名称 */
            name: 'impart系统',
            /** 功能描述 */
            dsc: '多人在线银趴系统',
            /** https://oicqjs.github.io/oicq/#events */
            event: 'message',
            /** 优先级，数字越小等级越高 */
            priority: 3000,
            rule: funs.map((fun) => ({
                reg: fun.regex,
                fnc: 'impart'
            }))
        })
    }

    async impart(e) {
        let params = getFunAndParams(e)
        if (params.error) {
            e.reply(params.reply)
            return false
        }
        let url = params.url
        // 检查是否触发了cd
        let isCD = await checkCD(e)
        // 如果触发了cd，直接返回
        if (isCD) {
            let msg = isCD
            this.reply(msg)
            return true
        }
        let res = await fetch(url).catch((err) => (logger.error(err)))
        if (!res) return await this.reply('接口请求失败，请先更新插件或联系群433567006')
        let status = await getStatus(res)
        if (status === 200) {
            let str = await modifyText(res, e)
            if (params.fun == 'player_group_rank') str = str.replace(/\\n/g, "\n")
            if (params.fun == 'suo') {
                if (!e.at) {
                    let reg = /【(.*?)】/g
                    let matches = str.match(reg)
                    if (matches && matches.length >= 1 && matches[0] === matches[1]) {
                        let count = 0
                        str = str.replace(reg, function (match) { count++; return count === 2 ? '自己' : match })
                        str = str.replace(/对方/g, '自己')
                    }
                }
            }
            await this.reply(`${str}`)
            await cancelCD(e, str)
        } else {
            switch (params.fun) {
                case 'pk':
                case 'query':
                    this.e.reply("你的或者对方的牛牛还没长出来，快去群里#生成牛牛吧！")
                    break
                default:
                    this.e.reply("未知错误")
                    break
            }
        }
    }
}